using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using YourNamespace.Services.Interfaces;
using Microsoft.Extensions.Logging;

namespace YourNamespace.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class QiniuController : ControllerBase
    {
        private readonly IQiniuService _qiniuService;
        private readonly ILogger<QiniuController> _logger;

        public QiniuController(IQiniuService qiniuService, ILogger<QiniuController> logger)
        {
            _qiniuService = qiniuService;
            _logger = logger;
        }

        [HttpGet("token")]
        public IActionResult GetUploadToken()
        {
            try
            {
                var token = _qiniuService.GetUploadToken();
                return Ok(new { token });
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "获取上传凭证失败");
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpPost("upload/signature")]
        public async Task<IActionResult> UploadSignature(IFormFile file, [FromQuery] string patientId)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return BadRequest(new { message = "没有接收到文件" });
                }

                if (string.IsNullOrEmpty(patientId))
                {
                    return BadRequest(new { message = "患者ID不能为空" });
                }

                using (var stream = file.OpenReadStream())
                {
                    var url = await _qiniuService.UploadSignatureAsync(stream, patientId);
                    return Ok(new { url });
                }
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "上传签名失败");
                return BadRequest(new { message = ex.Message });
            }
        }

        [HttpDelete("{fileKey}")]
        public async Task<IActionResult> DeleteFile(string fileKey)
        {
            try
            {
                var result = await _qiniuService.DeleteFileAsync(fileKey);
                if (result)
                {
                    return Ok(new { message = "文件删除成功" });
                }
                return BadRequest(new { message = "文件删除失败" });
            }
            catch (System.Exception ex)
            {
                _logger.LogError(ex, "删除文件失败");
                return BadRequest(new { message = ex.Message });
            }
        }
    }
} 